/**
 * Created by 55456 on 2016/4/12.
 */
var db = require("../models/index");
var Msg = db.models.Msg;
var User = db.models.User;

var addMsg = function *(sendID,revID,content){
    var msgID = yield Msg.create({
        sendID:sendID,
        revID:revID,
        content:content
    });
    return {msgID:msgID};
};

var getAllMsg = function *(sendID,revID){
    var msgs = yield User.findOne({
       where:{
           id : sendID
       },
       attributes:['id'],
       include : [{
           model : Msg,
           as : 'sendMsg',
           where :{
               sendID : sendID,
               revID : revID
           },
           order : [["createdAt"]]
       },{
           model : Msg,
           as : 'revMsg',
           where : {
               sendID : revID,
               revID : sendID
           },
           order : [["createdAt"]]
       }]
    });
    return {msgs:msgs};
};

var GetAllMsgByUserId = function*(userId){
    var msgs = yield User.findOne({
        where:{
            id : userId
        },
        attributes:['id'],
        include : [{
            model : Msg,
            as : 'sendMsg',
            where :{
                sendID : userId
            },
            order : [["createdAt"]]
        },{
            model : Msg,
            as : 'revMsg',
            where : {
                revID : userId
            },
            order : [["createdAt"]]
        }]
    });
    return {msgs:msgs};
};

module.exports = {
    addMsg,
    getAllMsg,
    GetAllMsgByUserId
};